import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const actions = {}
const mutations = {
    handleUserID: (state, id) => {
        state.user_id = id
        // 把登录的用户的名保存到localStorage中，防止页面刷新，导致vuex重新启动，用户名就成为初始值（初始值为空）的情况
        localStorage.setItem('user_id', id)
    },
    handleUserName: (state, user_name) => {
        state.username = user_name
        // 把登录的用户的名保存到localStorage中，防止页面刷新，导致vuex重新启动，用户名就成为初始值（初始值为空）的情况
        localStorage.setItem('username', user_name)
    },
    handleNickName: (state, nick_name) => {
        state.nickname = nick_name
            // 把登录的用户的名保存到localStorage中，防止页面刷新，导致vuex重新启动，用户名就成为初始值（初始值为空）的情况
        localStorage.setItem('nickname', nick_name)
    },
    handleAvatar: (state, avatar_url) => {
        state.avatar_url = avatar_url
        localStorage.setItem('avatar_url', avatar_url)
    },
    handleRole: (state, role) => {
        state.role = role
        localStorage.setItem('role', JSON.stringify(role))
    },
    add_menu_path: (state, menu_path_map) => {
        state.menu_path_map = menu_path_map
        localStorage.setItem('menu_path_map', JSON.stringify(menu_path_map))
    },
}
const state = {
    user_id: 0 || localStorage.getItem('user_id'),
    username: '' || localStorage.getItem('username'),
    nickname: '' || localStorage.getItem('nickname'),
    avatar_url: localStorage.getItem('avatar_url') || require('./assets/avatar.jpg'),
    role: JSON.parse(localStorage.getItem("role")) || {},
    menu_path_map: JSON.parse(localStorage.getItem('menu_path_map')) || {}
}
// getters 只会依赖 state 中的成员去更新
const getters = {
    user_id: (state) => state.user_id,
    username: (state) => state.username,
    nickname: (state) => state.nickname,
    avatar_url: (state) => state.avatar_url,
    role: (state) => state.role,
    menu_path_map: (state) => state.menu_path_map
}

const store = new Vuex.Store({
    actions,
    mutations,
    state,
    getters
})
export default store